from fastapi import FastAPI
from fastapi_mcp import FastApiMCP
from pydantic import BaseModel
from typing import List

app = FastAPI(title="计算器 MCP 服务器")

# 定义数据模型
class NumbersInput(BaseModel):
    numbers: List[float]

class TwoNumbersInput(BaseModel):
    a: float
    b: float

# 1. 加法端点
@app.post("/add", operation_id="add_numbers")
async def add_numbers(input: NumbersInput):
    """将多个数字相加"""
    result = sum(input.numbers)
    return {
        "result": result,
        "operation": "addition",
        "numbers": input.numbers
    }

# 2. 减法端点  
@app.post("/subtract", operation_id="subtract_numbers")
async def subtract_numbers(input: TwoNumbersInput):
    """两数相减"""
    result = input.a - input.b
    return {
        "result": result,
        "operation": "subtraction",
        "a": input.a,
        "b": input.b
    }

# 3. 乘法端点
@app.post("/multiply", operation_id="multiply_numbers") 
async def multiply_numbers(input: NumbersInput):
    """多个数字相乘"""
    result = 1
    for num in input.numbers:
        result *= num
    return {
        "result": result,
        "operation": "multiplication",
        "numbers": input.numbers
    }

# 4. 除法端点
@app.post("/divide", operation_id="divide_numbers")
async def divide_numbers(input: TwoNumbersInput):
    """两数相除"""
    if input.b == 0:
        return {"error": "不能除以零"}
    result = input.a / input.b
    return {
        "result": result,
        "operation": "division",
        "a": input.a,
        "b": input.b
    }

# 调试：在创建 MCP 之前查看路由
print("=" * 80)
print("🔍 创建 MCP 之前的 FastAPI 路由:")
print("=" * 80)
for route in app.routes:
    if hasattr(route, 'methods') and hasattr(route, 'path'):
        operation_id = getattr(route, 'operation_id', 'N/A')
        print(f"  方法: {route.methods}, 路径: {route.path}, operation_id: {operation_id}")
print()

# 创建 MCP 服务器（明确排除 MCP 协议端点）
mcp = FastApiMCP(
    app, 
    name="Calculator Server",
    # 只包含我们定义的业务端点
    include_operations=["add_numbers", "subtract_numbers", "multiply_numbers", "divide_numbers"]
)

# 调试：查看 MCP 工具列表
print("=" * 80)
print(f"🛠️  MCP 工具列表 (共 {len(mcp.tools)} 个):")
print("=" * 80)
for i, tool in enumerate(mcp.tools, 1):
    print(f"{i}. 名称: {tool.name}")
    print(f"   描述: {tool.description}")
    if hasattr(tool, 'inputSchema'):
        print(f"   输入参数: {tool.inputSchema}")
    print()

# 挂载 MCP 服务器
mcp.mount_http()

# 调试：挂载后查看所有路由
print("=" * 80)
print("🔍 挂载 MCP 后的 FastAPI 路由:")
print("=" * 80)
for route in app.routes:
    if hasattr(route, 'methods') and hasattr(route, 'path'):
        operation_id = getattr(route, 'operation_id', 'N/A')
        print(f"  方法: {route.methods}, 路径: {route.path}, operation_id: {operation_id}")
print()
print("=" * 80)
print("✅ MCP 服务器已启动，监听端口: 8000")
print("📡 MCP 端点: http://localhost:8000/mcp")
print("=" * 80)

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

